package com.webridge.plm.test;

import org.apache.log4j.Logger;

import wt.log4j.LogR;
import wt.util.WTException;
import wt.util.WTProperties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 
 * @author Chuck  2019-08-19
 */
public class MailUtil {
    
    private static Logger logger = LogR.getLogger(MailUtil.class.getName());
    
    private static String mailHost;

    private static String mailFrom;

    private static Properties mailProperties = new Properties();

    static {
        try {
            mailHost = WTProperties.getLocalProperties().getProperty("wt.mail.mailhost");
            mailFrom = WTProperties.getLocalProperties().getProperty("wt.mail.from");
            mailProperties.put("mail.smtp.host", mailHost);
            mailProperties.put("mail.smtp.auth", "true");
            mailProperties.put("mail.smtp.user","kira.liu@x1929.com");
            mailProperties.put("mail.smtp.password","Kira2014");
        } catch (Throwable throwable) {
            logger.error("init property error:",throwable);
            throw new ExceptionInInitializerError(throwable);
        }
    }
 
    private MailUtil() {
        
    }
    
    /**
     * send text mail 
     * @param subject
     * @param content
     * @param
     * @throws WTException
     */
	public static void sendMail(String subject, String content,
                                List<InternetAddress> mailToList) throws WTException {
	    List<List<InternetAddress>> spliteList = spliteEmailUsers(mailToList);
        for (List<InternetAddress> emailList : spliteList) {
            sendMail("kira.liu@x1929.com", subject, content, null,emailList,null) ;
        }  
	}
    
    /**
     * send mail with attachment
     * @param subject
     * @param content
     * @param filePath
     * @param
     * @throws WTException
     */
    public static void sendMail(String subject, String content, String filePath, List<InternetAddress> mailToList) throws WTException {
        List<List<InternetAddress>> spliteList = spliteEmailUsers(mailToList);
        for (List<InternetAddress> emailList : spliteList) {
            sendMail(null, subject, content, filePath,emailList,null) ;
        }     
    }
    
    /**
     * send mail with attachment
     * @param subject
     * @param content
     * @param filePath
     * @param
     * @throws WTException
     */
    public static void sendMailTOAndCC(String subject, String content, String filePath, List<InternetAddress> mailToList, List<InternetAddress> cclist) throws WTException {
        sendMail(null, subject, content, filePath,mailToList,cclist) ;
    }
    
    /**
     * send text mail 
     * @param subject
     * @param content
     * @param
     * @param fromAdd
     * @throws WTException
     */
    public static void sendMail(String subject, String content, List<InternetAddress> mailToList, String fromAdd) throws WTException{
        List<List<InternetAddress>> spliteList = spliteEmailUsers(mailToList);
        for (List<InternetAddress> emailList : spliteList) {
            sendMail(fromAdd, subject, content, null,emailList,null) ;
        }     
    }
    
    public static String getMailFrom() {
        return mailFrom;
    }
    
    /**
     * send mail with attachment
     * @param subject
     * @param content
     * @param filePath
     * @param list
     * @throws WTException
     */
    public static void sendMail(String subject, String content, String filePath, List<InternetAddress> list, String mailFrom) throws WTException {
        List<List<InternetAddress>> spliteList = spliteEmailUsers(list);
        for (List<InternetAddress> emailList : spliteList) {
            sendMail(mailFrom, subject, content, filePath,emailList,null) ;
        }             
    }
    
    private static void sendMail(String mailFrom, String subject, String content, String filePath, List<InternetAddress> mainToList, List<InternetAddress> cclist) throws WTException {
       
        logger.debug("sendMail mailFrom==================>:"+mailFrom);
        logger.debug("sendMail subject==================>:"+subject);
        logger.debug("sendMail content==================>:"+content);
        logger.debug("sendMail filePath==================>:"+filePath);
        logger.debug("sendMail mainToList==================>:"+mainToList);
        logger.debug("sendMail cclist==================>:"+cclist);
        logger.debug("sendMail mailProperties==================>:"+mailProperties);
        Authentication authentication = new Authentication(mailProperties.getProperty("mail.smtp.user"),mailProperties.getProperty("mail.smtp.password"));
        Session session = Session.getDefaultInstance(mailProperties, authentication);
        MimeMessage message = new MimeMessage(session);
        try {
            Transport transp = session.getTransport("smtp");
            transp.connect();
            if(mailFrom == null || "".equals(mailFrom)){
                message.setFrom(new InternetAddress(MailUtil.mailFrom));
            }
            else{
                message.setFrom(new InternetAddress(mailFrom));
            }
            logger.debug("mail from is :"+message.getFrom()[0]);
            if(mainToList!=null && !mainToList.isEmpty()) {
                
                message.addRecipients(Message.RecipientType.TO, mainToList.toArray(new InternetAddress[mainToList.size()]));
            }
            
            if(cclist!=null && !mainToList.isEmpty()){
                message.addRecipients(Message.RecipientType.CC, cclist.toArray(new InternetAddress[cclist.size()]));
            }
            
            message.setSubject(subject);
            
            Multipart multipart = new MimeMultipart();
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            if((content==null || "".equals(content.trim()))  &&  (filePath == null || "".equals(filePath.trim())) ){
                messageBodyPart.setContent("No Data", "text/html; charset=UTF-8");
            }
            else{
                messageBodyPart.setContent(content, "text/html; charset=UTF-8");
            }
            multipart.addBodyPart(messageBodyPart);
      
            File file=null;
            if(filePath != null && !"".equals(filePath)) {
                 MimeBodyPart fileBodyPart = new MimeBodyPart();
                 file = new File(filePath);
                 if(file.exists()) {
                     fileBodyPart.setFileName(file.getName());
                     DataSource source = new FileDataSource(filePath);
                     fileBodyPart.setDataHandler(new DataHandler(source));
                     multipart.addBodyPart(fileBodyPart);
                 }
            }
            message.setContent(multipart);
            Transport.send(message,message.getAllRecipients());
            if (file != null && file.exists()) {
                file.delete();
            }
        } catch (MessagingException e) {
            logger.error("send mail error:",e);
            throw new WTException(e);
        }
    }
    
    /**
     * 
     * @param emailList
     * @return
     */
	public static List<List<InternetAddress>> spliteEmailUsers(
			List<InternetAddress> emailList) {
	    List<List<InternetAddress>> resultList = new ArrayList<List<InternetAddress>>();
	    if(emailList==null || emailList.isEmpty()){
	        return resultList;
	    }
		String emailSize = "300";
		int userListSize = 0;
		try{
			userListSize = Integer.parseInt(emailSize);
		}catch(NumberFormatException e){
			userListSize = emailList.size() ;
		}
		int loopCount = (emailList.size() % userListSize == 0) ? (emailList.size() / userListSize)
				: ((emailList.size() / userListSize) + 1);
		for (int i = 0; i < loopCount; i++) {
			int startNum = i * userListSize;
			int endNum = (i + 1) * userListSize;
			if (i == loopCount - 1) {
				endNum = emailList.size();
			}
			List<InternetAddress> listObjSub = emailList.subList(startNum,
					endNum);
			resultList.add(listObjSub);
		}
		logger.debug("resultList==================>:"+resultList);
		return resultList;
	}
}
